#include<iostream>
#include<sys/types.h>
#include<unistd.h>
#include<assert.h>
#include<sys/wait.h>
#include<string.h>

using std::cout;
using std::endl;

int main()
{
    int fd[2];
    assert(pipe(fd) == 0);

    pid_t id = fork();
    assert(id != -1);

    if (id == 0)//child
    {
        close(fd[0]);//关闭读通道
        char buffer[1024];
        int cnt = 0;
        memset(buffer, 0 , sizeof(buffer));
        while(true)
        {
            cnt++;
            sprintf(buffer, "我是子进程# pid: %d cnt: %d\n", getpid(), cnt);
            cout << buffer << endl;
            ssize_t n = write(fd[1], buffer, strlen(buffer));
            assert(n != -1);
            sleep(1);
        }
        exit(0);
    }

    if (id > 0)//parent
    {
        char buffer[1024];
        memset(buffer, 0, sizeof(buffer));
        close(fd[1]);//关闭写通道

        while(true)
        {
            ssize_t read_flag = read(fd[0], buffer, sizeof(buffer) - 1);
            assert(read_flag != -1);
            
            if(read_flag != 0)
            {
                cout << read_flag << endl;
                std::cout << "我是父进程# pid: " << getpid() << " | " << buffer <<std::endl;
                memset(buffer, 0, sizeof(buffer));
            }            
        }
    }
    pid_t child_statu = waitpid(id, nullptr, WNOHANG);
    assert(child_statu != -1);
    return 0;
}